from django.shortcuts import render

# Create your views here.

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin

from rest_framework.views import  APIView
from rest_framework.response import Response
from lib.al_pay import gateway,alipay

## 之前测试代码
# class PayView(APIView):
#     def post(self,request,*args,**kwargs):
#         subject = "充气娃娃"
#         # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
#         order_string = alipay.api_alipay_trade_page_pay(
#             out_trade_no="20161112",
#             total_amount=1000,
#             subject=subject,
#             return_url="https://www.baidu.com",
#             notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
#         )
#         print(order_string)
#         pay_url=gateway+ '?' + order_string
#         print(pay_url)
#         return Response({'pay_url':pay_url})

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from .models import Order
from .serializer import PayOrderSerializer
from utils.response import APIResponse
class PayView(GenericViewSet,CreateModelMixin):
    queryset = Order.objects.all()
    serializer_class = PayOrderSerializer
    # 认证类，需要搭配权限类--->保证必须登录才能用
    # 只使用下面一个：（JSONWebTokenAuthentication）
    # 用户可以登录，也可以不登录，
    # 如果登录了后续能之间获取request.user
    # 如果没有登录，就获取不到
    authentication_classes = [JSONWebTokenAuthentication,]
    permission_classes = [IsAuthenticated,]

    # 重写create，控制返回的数据
    def create(self, request, *args, **kwargs):
        ser=self.get_serializer(data=request.data,context={'request':request})
        ser.is_valid(raise_exception=True)
        #保存
        self.perform_create(ser)
        # ser.save()  跟跟上面一样

        pay_url=ser.context.get('pay_url')

        return APIResponse(msg='订单创建成功',pay_url=pay_url)


from rest_framework.views import APIView
from utils.logging import get_logger
logger=get_logger('pay')
class PaySuccess(APIView):
    def get(self,request,*args,**kwargs): # 咱们前端回调的
        out_trade_no=request.GET.get('out_trade_no')
        # 去数据库查询该订单是否已经支付完成
        order=Order.objects.filter(out_trade_no=out_trade_no,order_status=1).first()
        if order: # post回调回调完了，订单状态改了
            return APIResponse(msg='支付成功')
        else:
            return APIResponse(status=1,msg='暂未支付成功')


    def post(self,request,*args,**kwargs): # 支付宝回调
        # 验签，通过，修改订单状态，返回给支付宝success
        try:

            result_data = request.data.dict()  # 一定不能忘
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign') # 签名，必须验证签名
            print('支付宝返回的数据：',result_data)
            from lib import al_pay
            result = al_pay.alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')  # 必须返回给支付宝，否则支付宝会一直回调
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')